package com.itheima.reggie.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.utils.BaseContext;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器
 */
//@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换req和resp
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //放行不拦截字符
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login"
        };

        String reqUri = request.getRequestURI();

        //不能拼接带星的所以要使用一个对象
      boolean flag =  requestUri(urls,reqUri);
      if(flag){
          //true则放行
          filterChain.doFilter(request,response);
          return;
      }

        //取出session中的员工id
        //有员工id就放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if(empId != null){
            //存储员工id
            BaseContext.set(empId);
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //把响应传到前端
        ObjectMapper objectMapper = new ObjectMapper();
        String notLogin = objectMapper.writeValueAsString(R.error("NOTLOGIN"));
        response.getWriter().write(notLogin);
    }

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    private  boolean requestUri(String[] urls, String reqUri) {
        for (String url : urls) {
            boolean match = pathMatcher.match(url, reqUri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
